/**
 * 
 */
package net.xfok;

import java.util.Iterator;
import java.util.Map;

import net.xfok.dict.DictEngine;
import net.xfok.dict.Location;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * @author howard
 * 
 */
public class Dict extends Activity implements OnClickListener{
	private static final String TAG="Dict";
	private static final String DICT_NAME="xdict";
	private static final String DICT_PATH="/sdcard/";
	private Button btSearch;
	private EditText key;
	private TextView result;
	private DictEngine dict;
	private Map<String,Location> results;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dict);
		btSearch=(Button)findViewById(R.id.search);
		btSearch.setOnClickListener(this);
		key=(EditText)findViewById(R.id.key);
		result=(TextView)findViewById(R.id.result);	
		dict=new DictEngine(DICT_PATH, DICT_NAME);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.search:
			search();
			break;
		default:
			break;
		}
	}
	
	private void search(){
//		if(dict!=null){
			String word=key.getText().toString();
			results=dict.getSearchMatchList(word);
			StringBuffer sb=new StringBuffer();
			String mean=null;
			if(results!=null&&!results.isEmpty()){
				Iterator it=results.entrySet().iterator();			
	    		while(it.hasNext()){
	    			Map.Entry entry = (Map.Entry) it.next();
	    			if(mean==null){
	    				mean=lookup(entry.getKey().toString());
	    			}
	    			sb.append(entry.getKey().toString()).append(",");
	    		}
			}
			sb.append("\n mean:").append(mean);
			result.setText(sb.toString());
//		}
	}

	public String lookup(String key){   	
    	String mean=null;
        try {
        	long start = System.currentTimeMillis(); 
        	if(dict!=null){
        		mean=dict.getExplanation(results.get(key));
        	}
            long end = System.currentTimeMillis();
            Log.i(TAG, "look up time:"+(end-start));
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return mean;
    }
}
